import {useCallback, useEffect, useRef} from "react"

// @ts-ignore
const useDebounce: Function = (fn: Function, delay: number, dep: any[] = []) => {
    const {current} = useRef({fn, timer: null});
    useEffect(() => {
        current.fn = fn;
    }, [fn]);

    return useCallback(function (...args: any) {
        return new Promise((resolve: any, reject: any) => {
            if (current.timer) {
                clearTimeout(current.timer)
            }
            // @ts-ignore
            current.timer = setTimeout(() => {
                // @ts-ignore
                let res: any = current.fn.call(this, ...args);
                resolve(res);
            }, delay)
        });
    }, dep)
}

export default useDebounce;